package com.rongshu.view.penpal.present;

import android.Manifest;
import android.app.Activity;
import android.content.Context;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.rongshu.api.FileUploadService;
import com.rongshu.api.RetorfitService;
import com.rongshu.utils.Common;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.mvp.BasePresenter;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.home.bean.LabelResponse;
import com.rongshu.view.penpal.bean.EditPenpalMsgBody;
import com.rongshu.view.penpal.view.NewPenpalView;
import com.rongshu.view.userInfo.entity.UpLoadImage;
import com.utils.permissions.OnPermission;
import com.utils.permissions.XXPermissions;
import com.widget.toast.ToastUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.functions.Action0;

/**
 * created by zhengweis on 2018/11/29.
 * description：
 */
public class NewPenpalPresenter extends BasePresenter<NewPenpalView> {
    private String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private StringBuilder sb = new StringBuilder();

    public NewPenpalPresenter(Context context) {
        super(context);
    }

    /**
     * @param district   笔会地址
     * @param signatures 笔会签名
     * @param penpalName 笔会名
     * @param base64     笔会头像地址
     * @param label      选择的标签
     * @param custom     自定义的标签
     */
    public void submitMsg(String district, String signatures, String penpalName, String base64, String label, String custom) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("district", district);
        String sign = Common.encryptionSign(map);
        EditPenpalMsgBody body = new EditPenpalMsgBody();
        body.setBase64(base64);
        body.setCustom(custom);
        body.setLabel(label);
        body.setPenclubname(penpalName);
        body.setSignatures(signatures);
        RetorfitService.createPenpal(UserInfoUtils.getUserId(), district,
                sign, body).doOnSubscribe(new Action0() {
            @Override
            public void call() {

            }
        }).subscribe(new Subscriber<INetBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(INetBean object) {
                if (object.getErrCode() == 0) {
                    getView().callBackSubmitResult();
                } else {
                    getView().INetFaild(object.getErrMsg());
                }
            }
        });
    }

    //检查是否已经添加过自定义标签
    public boolean checkIsAddCustomLabel(List<LabelResponse.ResponseBean> selectedLabels) {
        for (LabelResponse.ResponseBean bean : selectedLabels) {
            if (bean.getId() == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * base64图片上传
     */
    public void postUploadFileBase64(String path) {
        //构建要上传的文件
        File file = new File(path);
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("AndroidFile", file.getName(), requestFile);
        FileUploadService.upload(body).doOnSubscribe(new Action0() {
            @Override
            public void call() {

            }
        }).subscribe(new Subscriber<UpLoadImage>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(UpLoadImage upLoadImageResult) {
                if (upLoadImageResult.getErrCode() == 0) {
                    UpLoadImage.ResponseBean response = upLoadImageResult.getResponse();
                    if (response != null && response.getImgUrl() != null){
                        String url = response.getImgUrl().get(0);
                        getView().callBackUploadImg(url);
                    } else {
                        ToastUtils.show(upLoadImageResult.getErrMsg());
                    }
                } else {
                    getView().INetFaild(upLoadImageResult.getErrMsg());
                }
            }
        });
    }

    public void getPicture() {
        if (!XXPermissions.isHasPermission(mContext, permissions)) {
            XXPermissions.with((Activity) mContext).permission(permissions).request(new OnPermission() {
                @Override
                public void hasPermission(List<String> granted, boolean isAll) {
                    toGallery();
                }

                @Override
                public void noPermission(List<String> denied, boolean quick) {
                    XXPermissions.gotoPermissionSettings(mContext);
                }
            });
        } else {
            toGallery();
        }

    }

    private void toGallery() {
        PictureSelector.create((Activity) mContext)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .withAspectRatio(1, 1)
                .previewImage(true)
                .isCamera(true)
                .enableCrop(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 获取选择的系统标签
     */
    public String getSelectedLabels(List<LabelResponse.ResponseBean> selectedLabels) {
        sb.delete(0, sb.length());
        for (int i = 0; i < selectedLabels.size(); i++) {
            sb.append(selectedLabels.get(i).getId());
            if (i < selectedLabels.size() - 1) {
                sb.append(",");
            }
        }
        return sb.toString();
    }

    /**
     * 获取选择的自定义标签
     */
    public String getSelectedCustomLabel(List<LabelResponse.ResponseBean> selectedLabels) {
        for (LabelResponse.ResponseBean bean : selectedLabels) {
            if (bean.getId() == 0) {//自定义的标签id==0
                return bean.getTitle();
            }
        }
        return "";
    }
}
